#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>

#include <cstdio>
#include <unistd.h>
#include <string.h>

const int BUF_SIZE = 1024;

int main(int argc, char** argv)
{
    if (argc < 2) {
         printf("usage: client <serverip>");
    }
    int sock;
    sockaddr_in address;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        perror("Unable to create socket");
        return 1;
    }

    address.sin_family = AF_INET;
    address.sin_port = htons(5001);
    inet_aton(argv[1], (in_addr *)address.sin_addr.s_addr);
    if(connect(sock, (sockaddr *)&address, sizeof(address)) < 0)
    {
        perror("Unable to connect");
        return 1;
    }

    char s[BUF_SIZE];
    char read_buffer[BUF_SIZE];
    int bytes_sent = 0;
    int bytes_read = 0;


    while (true) {
        fgets(s, BUF_SIZE, stdin);
        int s_len = strlen(s);
        bytes_sent = 0;
        while(true) {
            bytes_sent += send(sock, s + bytes_sent, s_len - bytes_sent, 0);
            if (bytes_sent == s_len) break;
        }

        bytes_read = recv(sock, read_buffer, BUF_SIZE, 0);
        read_buffer[bytes_read - 1] = '\0';
        printf("%s\n", read_buffer);
    }
    close(sock);
    return 0;
}
